/***************************mainwindow.cpp*****************************/
/**********************************************************************/
/*******************Browsers Daily Build Updater***********************/
/************Copyright (C) 2010-2011  Gianluigi Biancucci**************/
/**********************************************************************/
/*****This is free software, and you are welcome to redistribute it****/
/*****and / or modify underthe terms of GPLV2 License.*****************/
/*****This program comes with ABSOLUTELY NO WARRANTY*******************/
/**********************************************************************/

#include "stdlib.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "singletondownloader.h"
#include "iostream"
#include "QFile"
#include <QMessageBox>
#include <QIcon>
#include <QLabel>
#include <QDir>
#include <QProcess>
#include <QStringList>
#include "UpdaterFactory.h"
#include "firefoxupdater.h"
#include"IBrowserUpdater.h"
#include "paths.h"
#include "proxydialog.h"
#include <QProgressBar>
#include "settingsdialog.h"
#include "setfilehandler.h"
#include "loadingdialog.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    process = new QProcess(this);
    setFileH=SetFileHandler::getInstance();
    QObject::connect(ui->mainToolBar->addAction("Settings"),SIGNAL(triggered()),this, SLOT(settings()));
    QObject::connect(ui->mainToolBar->addAction("Set Proxy"),SIGNAL(triggered()),this, SLOT(proxy()));
    QObject::connect(ui->mainToolBar->addAction("Help"),SIGNAL(triggered()),this, SLOT(help()));
    QObject::connect(ui->mainToolBar->addAction("About"),SIGNAL(triggered()),this, SLOT(about()));
    updater=0;

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_checkButton_clicked(){
    this->setupFactory();
    if(updater==0) updater=UpdaterFactory::getInstance();
    else{
        delete updater;
        updater=UpdaterFactory::getInstance();
    }
    if(updater!=0){

        ui->checkButton->setDisabled(true);
        ui->checkButton->setText("Checking...");
        QString lastVer;
        QString installedVer;


        if(!updater->checkInstallPath()){
            QMessageBox msg;
            msg.setIcon(QMessageBox::Information);
            msg.setText("It seems that there isn't "+updater->getBrowserName()+" installed in the selected path. If you want to\nupdate a previous "+updater->getBrowserName()+" installation you had to select the folder where executable file is.\nOtherwise, if you want to create a fresh new installation in this path without\nupdate anything click OK to continue downloading the latest version of "+updater->getBrowserName());
            msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
            msg.setDefaultButton(QMessageBox::Ok);
            ui->checkButton->setText("Check now");
            ui->checkButton->setEnabled(true);
            int c = msg.exec();
            if(c == 1024) {
                this->downNUpd();
            }

        }else {

            if(!updater->getLatestVersion(&lastVer)) {
                QMessageBox error;
                error.setText(updater->getLastError());
                error.setIcon(QMessageBox::Warning);
                error.exec();
                ui->checkButton->setText("Check now");
                ui->checkButton->setEnabled(true);
                return;
            }


            if(!updater->getInstalledVersion(&installedVer)) {
                QMessageBox error;
                error.setText(updater->getLastError());
                error.setIcon(QMessageBox::Warning);
                error.exec();
                ui->checkButton->setText("Check now");
                ui->checkButton->setEnabled(true);
                return;
            }

            if(lastVer == installedVer){
                QMessageBox msg;
                msg.setWindowTitle("Already up to date");
                msg.setIcon(QMessageBox::Information);
                msg.setText("No new version of "+updater->getBrowserName()+" present. \nYou're already up to date.");
                msg.exec();
            }
            else {
                QMessageBox msg;
                msg.setWindowTitle("New version avaiable");



                msg.setText("There is a new version of "+updater->getBrowserName()+". Do you want to download it?");
                msg.setIcon(QMessageBox::Question);
                msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
                msg.setDefaultButton(QMessageBox::Ok);

                int c = msg.exec();
                if(c == 1024) {
                    this->downNUpd();
                }
            }



        }



        ui->checkButton->setText("Check now");
        ui->checkButton->setEnabled(true);





    }else{
        QMessageBox error;
        error.setText("Select a Browser!");
        error.setIcon(QMessageBox::Warning);
        error.exec();
    }
}


void MainWindow::downNUpd(){
    LoadingDialog* lDialog = new LoadingDialog(this);
    lDialog->setValues(0,100,0);
    QObject::connect(SingletonDownloader::getInstance(), SIGNAL(nextStep()),lDialog, SLOT(nextStep()));
    lDialog->showIt();


    QString exePath;
    if(  updater->downloadLatest(&exePath)){
        lDialog->close();

        QMessageBox msg;
        msg.setWindowTitle("Download Complete");
        msg.setText(updater->getBrowserName()+" installer saved in: "+exePath+" .\n\n Do you want to install it right now?");
        msg.setIcon(QMessageBox::Question);
        msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msg.setDefaultButton(QMessageBox::Cancel);

        int c = msg.exec();
        if(c==1024){

            if(!updater->install(exePath)){
                msg.close();
                QMessageBox error;
                error.setText(updater->getLastError());
                error.setIcon(QMessageBox::Warning);
                error.exec();

            }
        }

    } else {
        QMessageBox error;
        error.setText(updater->getLastError());
        error.setIcon(QMessageBox::Warning);
        error.exec();
    }


}
QString MainWindow::getOperaPath(){

    QString customPath;
    if(setFileH->readOperaCustomPath(&customPath)){
        if(!customPath.isEmpty())
            return customPath;
        else {
            QString def32 ="[Default] ";
            def32+=OPERA32DEFPATH;
            return  def32;}

    }else {
        QString error= setFileH->getLastError();
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText(error);
        msg.exec();
        return error;
    }

}
QString MainWindow::getChromiumPath(){
    QString customPath;
    if(setFileH->readChroCustomPath(&customPath)){
        if(!customPath.isEmpty())
            return customPath;
        else {
            QString def32 ="[Default] ";
            def32+=CHRO32DEFPATH;
            return  def32;}

    }else {
        QString error= setFileH->getLastError();
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText(error);
        msg.exec();
        return error;
    }

}


QString MainWindow::getFirefoxPath(){

    QString customPath;
    if(setFileH->readFfoxCustomPath(&customPath)){
        if(!customPath.isEmpty())
            return customPath;
        else{
            if(ui->radio32->isChecked()){
                QString def32 ="[Default] ";
                def32+=FFOX32DEFPATH;
                return  def32;}
            else{
                QString def64 ="[Default] ";
                def64+=FFOX64DEFPATH;
                return  def64;}
        }
    }else {
        QString error= setFileH->getLastError();
        QMessageBox msg;
        msg.setWindowTitle("Error");
        msg.setText(error);
        msg.exec();
        return error;
    }

}


void MainWindow::on_radio32_clicked(){
    currArch="32";
    //Only firefox have 64 bit version till now.
    if(ui->firefoxradio->isChecked())
        this->setFirefoxPathLabel();

}

void MainWindow::on_radio64_clicked(){
    currArch="64";
    //Only firefox have 64 bit version till now.
    if(ui->firefoxradio->isChecked())
        this->setFirefoxPathLabel();
}

void MainWindow::on_firefoxradio_clicked(){
    currUpdater=ui->firefoxradio->text();
    this->setFirefoxPathLabel();
    ui->radio64->setEnabled(true);

}

void MainWindow::on_chromiumradio_clicked(){
    currUpdater=ui->chromiumradio->text();
    this->setChromiumPathLabel();

    ui->radio64->setEnabled(false);
    ui->radio32->setChecked(true);

}

void MainWindow::on_operaradio_clicked(){
    currUpdater=ui->operaradio->text();
    this->setOperaPathLabel();    
    ui->radio64->setEnabled(false);
    ui->radio32->setChecked(true);

}

void MainWindow::setOperaPathLabel(){
    currPath=this->getOperaPath();
    ui->pathLabel->setText("Opera folder: "+currPath);
    currPath.replace("[Default] ","");
}

void MainWindow::setChromiumPathLabel(){
    currPath=this->getChromiumPath();
    ui->pathLabel->setText("Chromium folder: "+currPath);
    currPath.replace("[Default] ","");
}

void MainWindow::setFirefoxPathLabel(){
    currPath=this->getFirefoxPath();
    ui->pathLabel->setText("Firefox folder: "+currPath);
    currPath.replace("[Default] ","");
}


void MainWindow::setupFactory(){
    UpdaterFactory::setArch(currArch);
    UpdaterFactory::setUpdater(currUpdater);
    UpdaterFactory::setPath(currPath);
}


void MainWindow::refreshPathLabel(){
    if(ui->operaradio->isChecked()){
        this->setOperaPathLabel();
    }
    if(ui->chromiumradio->isChecked()){
        this->setChromiumPathLabel();
    }
    if(ui->firefoxradio->isChecked()){
        this->setFirefoxPathLabel();
    }
}

void MainWindow::settings(){

    SettingsDialog* setDialog=new SettingsDialog(this);
    setDialog->setModal(true);
    setDialog->exec();
    this->refreshPathLabel();

}

void MainWindow::proxy(){

    ProxyDialog* dialog= new ProxyDialog(this);
    dialog->show();

}

void MainWindow::help(){
    QMessageBox msg;
    msg.setWindowTitle("About BDBU 0.2.1");
    msg.setIcon(QMessageBox::Information);
    QString strMsg="This simple program will check, download and update for you the latest daily build for the selected browser.\n\n";
    strMsg+="Sometimes these builds are very unstable and you choose to use it at your own risk.\n";
    strMsg+="This program checks if there is a newer browser version than the one installed on your pc (you've to enter the browser install path in settings ";
    strMsg+=", if not it tries to use the default path)";
    msg.setText(strMsg);
    msg.exec();
}

void MainWindow::about(){
    QMessageBox msg;
    msg.setWindowTitle("About BDBU.");
    msg.setIcon(QMessageBox::Information);
    QString strMsg="Created by Gianluigi Biancucci\n";
    strMsg+="gianluigi85@gmail.com\n\n";
    strMsg+="This program is Free software\n";
    strMsg+="and is distribuited WITHOUT ANY WARRANTY.\n";
    strMsg+="You can redistribuite it and / or modify it\n";
    strMsg+="under the terms and condition of GPLV2 license.\n\n";
    strMsg+="For more information see:\nhttp://www.gnu.org/licenses";
    msg.setText(strMsg);
    msg.exec();
}

